<template>
  <div class="death-cancel">
    <el-card>
      <template #header>
        <span>死亡注销</span>
      </template>
      
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <!-- 身份证号输入 -->
        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item label="身份证号" prop="idCard">
              <el-input 
                v-model="form.idCard" 
                placeholder="请输入死者身份证号" 
                @blur="handleIdCardBlur"
                @input="handleIdCardInput"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-button 
              type="primary" 
              @click="fetchPersonInfo" 
              :loading="personLoading"
              :disabled="!form.idCard"
            >
              查询信息
            </el-button>
          </el-col>
        </el-row>

        <!-- 人员信息显示 -->
        <div v-if="personInfo.name" class="person-info">
          <el-divider content-position="left">死者信息</el-divider>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="姓名">{{ personInfo.name }}</el-descriptions-item>
            <el-descriptions-item label="身份证号">{{ form.idCard }}</el-descriptions-item>
            <el-descriptions-item label="性别">{{ getGenderText(personInfo.gender) }}</el-descriptions-item>
            <el-descriptions-item label="出生日期">{{ personInfo.birthDate || '未知' }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 提交按钮 -->
        <el-form-item style="margin-top: 30px;">
          <el-button 
            type="danger" 
            @click="handleSubmit" 
            :loading="loading"
            :disabled="!personInfo.name"
          >
            确认死亡注销
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 注销须知 -->
      <el-card class="notice-card" shadow="never" style="margin-top: 20px;">
        <template #header>
          <span>注销须知</span>
        </template>
        <div class="notice-content">
          <el-alert
            title="重要提示"
            type="warning"
            :closable="false"
            show-icon
          >
            <p>死亡注销后该人员的户籍信息将被标记为无效，此操作不可撤销，请谨慎操作。</p>
          </el-alert>
          
          <h4 style="margin-top: 15px;">操作流程：</h4>
          <ol>
            <li>输入死者身份证号</li>
            <li>系统自动查询并显示人员信息</li>
            <li>确认信息无误后点击"确认死亡注销"</li>
            <li>系统处理注销申请</li>
          </ol>
        </div>
      </el-card>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 表单引用
const formRef = ref()

// 表单数据
const form = reactive({
  idCard: ''
})

// 人员信息
const personInfo = reactive({
  name: '',
  gender: '',
  birthDate: ''
})

// 加载状态
const loading = ref(false)
const personLoading = ref(false)

// 表单验证规则
const rules = {
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { 
      pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, 
      message: '请输入正确的身份证号格式', 
      trigger: 'blur' 
    }
  ]
}

// 获取token
const getToken = () => {
  return localStorage.getItem('token') || sessionStorage.getItem('token')
}

// 身份证号输入处理
const handleIdCardInput = () => {
  // 清空之前的人员信息
  personInfo.name = ''
  personInfo.gender = ''
  personInfo.birthDate = ''
}

// 身份证号失焦处理
const handleIdCardBlur = () => {
  if (form.idCard && form.idCard.length === 18) {
    fetchPersonInfo()
  }
}

// 日期格式化工具函数
const formatDate = (dateValue) => {
  if (!dateValue) return ''
  
  let date
  // 如果是时间戳数字，转换为Date对象
  if (typeof dateValue === 'number') {
    date = new Date(dateValue)
  } else if (typeof dateValue === 'string') {
    date = new Date(dateValue)
  } else if (dateValue instanceof Date) {
    date = dateValue
  } else {
    return ''
  }
  
  // 检查日期是否有效
  if (isNaN(date.getTime())) {
    return ''
  }
  
  // 格式化为 YYYY-MM-DD
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  
  return `${year}-${month}-${day}`
}

// 获取人员信息
const fetchPersonInfo = async () => {
  if (!form.idCard) {
    ElMessage.warning('请先输入身份证号')
    return
  }

  // 验证身份证号格式
  const idCardPattern = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
  if (!idCardPattern.test(form.idCard)) {
    ElMessage.error('请输入正确的身份证号格式')
    return
  }

  personLoading.value = true
  
  try {
    const token = getToken()
    if (!token) {
      ElMessage.error('未找到登录凭证，请重新登录')
      return
    }

    const response = await axios.get(`http://localhost:8088/person/getByIdCard`, {
      params: {
        idCard: form.idCard
      },
      headers: {
        'token': token,
        'Content-Type': 'application/json'
      }
    })

    console.log('获取人员信息响应:', response.data)

    if (response.data && response.data.status === 200) {
      const data = response.data.data
      if (data) {
        personInfo.name = data.name || ''
        personInfo.gender = data.gender || ''
        personInfo.birthDate = formatDate(data.birthDate) // 使用格式化函数处理日期
        ElMessage.success('人员信息获取成功')
      } else {
        ElMessage.warning('未找到该身份证号对应的人员信息')
        // 清空人员信息
        personInfo.name = ''
        personInfo.gender = ''
        personInfo.birthDate = ''
      }
    } else {
      ElMessage.error(response.data?.msg || '获取人员信息失败')
      // 清空人员信息
      personInfo.name = ''
      personInfo.gender = ''
      personInfo.birthDate = ''
    }
  } catch (error) {
    console.error('获取人员信息失败:', error)
    ElMessage.error('获取人员信息失败，请检查网络连接')
    // 清空人员信息
    personInfo.name = ''
    personInfo.gender = ''
    personInfo.birthDate = ''
  } finally {
    personLoading.value = false
  }
}

// 获取性别文本
const getGenderText = (gender) => {
  if (gender === '1' || gender === 1) return '男'
  if (gender === '0' || gender === 0) return '女'
  return '未知'
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  // 验证表单
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return

  // 检查是否已获取人员信息
  if (!personInfo.name) {
    ElMessage.warning('请先查询人员信息')
    return
  }

  // 二次确认
  try {
    await ElMessageBox.confirm(
      `确认要对 ${personInfo.name}（身份证号：${form.idCard}）进行死亡注销吗？此操作不可撤销！`,
      '确认死亡注销',
      {
        confirmButtonText: '确认注销',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
  } catch {
    return // 用户取消
  }

  loading.value = true
  
  try {
    const token = getToken()
    if (!token) {
      ElMessage.error('未找到登录凭证，请重新登录')
      return
    }

    const response = await axios.put(`http://localhost:8088/household/deathCancellation`, null, {
      params: {
        idCard: form.idCard
      },
      headers: {
        'token': token,
        'Content-Type': 'application/json'
      }
    })

    console.log('死亡注销响应:', response.data)

    if (response.data && response.data.status === 200) {
      ElMessage.success('死亡注销成功')
      handleReset()
    } else {
      ElMessage.error(response.data?.msg || '死亡注销失败')
    }
  } catch (error) {
    console.error('死亡注销失败:', error)
    if (error.response?.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
    } else {
      ElMessage.error('死亡注销失败，请检查网络连接')
    }
  } finally {
    loading.value = false
  }
}

// 重置表单
const handleReset = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.idCard = ''
  personInfo.name = ''
  personInfo.gender = ''
  personInfo.birthDate = ''
}
</script>

<style scoped>
.death-cancel {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 60px);
}

.person-info {
  margin: 20px 0;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.notice-card {
  background-color: #fff;
}

.notice-content {
  line-height: 1.6;
}

.notice-content h4 {
  color: #303133;
  margin-bottom: 10px;
}

.notice-content ol {
  margin-left: 20px;
  color: #606266;
}

.notice-content ol li {
  margin-bottom: 8px;
}

.el-descriptions {
  margin-top: 10px;
}

.el-button--danger {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.el-button--danger:hover {
  background-color: #f78989;
  border-color: #f78989;
}

.el-alert {
  margin-bottom: 15px;
}

.el-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-form-item {
  margin-bottom: 22px;
}

.el-input {
  font-size: 14px;
}

.el-button {
  font-size: 14px;
  padding: 12px 20px;
}
</style>